package cn.com.web.Servlet;

import cn.com.domain.Order;
import cn.com.service.OrderService;
import cn.com.service.impl.OrderServiceImpl;
import cn.com.utils.Dateutils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/AddOrderServlet")
public class AddOrderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String order_room_name = request.getParameter("order_room_name");
        String order_customer_name = request.getParameter("order_customer_name");
        String order_start = request.getParameter("order_start");

        //判断日期是否是当天之后的
        String nowDate = Dateutils.getNowDate();
        int i = Dateutils.calculateDaysDifference(nowDate, order_start);
        if (i<=0)
        {
            request.setAttribute("error","添加订单失败,开始日期不能是以前的日期");
            request.getRequestDispatcher("FindOrderByPageServlet?currentPage=1&rows=5")
                    .forward(request,response);
            return;
        }

        String order_end = request.getParameter("order_end");
        int order_days = Dateutils.calculateDaysDifference(order_start,order_end);
        if (order_days<=0)
        {
            request.setAttribute("error","添加订单失败,截止日期大于或等于开始日期");
            request.getRequestDispatcher("FindOrderByPageServlet?currentPage=1&rows=5")
                    .forward(request,response);
            return;
        }
        //创建service对象
        OrderService service=new OrderServiceImpl();
        double order_price = service.findpriceByName(order_room_name) * order_days;
        Order order=new Order(0,order_room_name,order_customer_name,
                order_days,order_price,order_start,order_end,"未入住");
        boolean flag = service.addOrder(order);
        if (!flag)
            request.setAttribute("error","添加订单失败,剩余房间不足 ");
        else
            request.setAttribute("error",null);
        request.getRequestDispatcher("FindOrderByPageServlet?currentPage=1&rows=5")
                .forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
